<?php

	session_start();

	require_once("appconf.php");
	require_once("lib/utility.php");
	require_once("lib/class.Report.php");

	if(!isset($_SESSION['username'])) {
		header("HTTP/1.1 401 Unauthorized");
		die();
	}


	//Default list options
	$offset = 0;
	$amount	= 10;

	if (isset($_REQUEST["offset"])) {
		$offset = max(0, intval($_REQUEST["offset"]));
	}

	if (isset($_REQUEST["amount"])) {
		$amount = max(0, intval($_REQUEST["amount"]));
	}


	header("Content-Type: text/xml");
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";


	$dirName = $appRoot."data/".filenameSafe($_SESSION['username'])."/reports";



	$files = array();

	//Make sure template dir exist
	clearstatcache();
	if (is_dir($dirName)) {
		$handler = opendir($dirName);
		while ($file = readdir($handler)) {
			$filepath = $dirName."/".$file;
			if (!is_dir($filepath)) {
				array_push($files, array($file, filemtime($filepath)));
			}
		}
	}

	sortByDate($files);



	echo "<response max=\"".sizeof($files)."\">\n";
	for ($i=$offset; $i<min($offset+$amount, sizeof($files)); $i++) {
		$reportObj = new Report($_SESSION['username'], $files[$i][0]);
		echo "\t<report title=\"".$reportObj->getTitle()."\" filename=\"".$files[$i][0]."\" generated-on=\"".date("Y-m-d H:i:s", $files[$i][1])."\" built-in=\"".$reportObj->getBuiltIn()."\">\n";
		echo "\t</report>\n";
	}
	echo "</response>\n";

?>